package com.irs.irsforum.aop;

import com.alibaba.rocketmq.shade.com.alibaba.fastjson.JSONArray;
import com.irs.irsforum.entity.IndexPost;
import com.irs.irsforum.entity.Resources;
import com.irs.irsforum.utils.RecommendAlgorithm;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Liyihui
 * @Date: 2019/2/26
 * @Time: 10:18
 */
@Aspect
@Component
public class CacheListenerAop {

    private static final Logger logger =
            LoggerFactory.getLogger(CacheListenerAop.class);

    @Autowired
    private RedisTemplate redisTemplate;

    @Pointcut("execution(public * com.irs.irsforum.service.impl.BehaviorServiceImpl.setBehaviorType(..))" +
            "|| execution(public * com.irs.irsforum.service.impl.BehaviorServiceImpl.updateBehavior(..))")
    public void indexRecommendPointCut() {
    }


    @After("indexRecommendPointCut()")
    public void refreshRecommendPost(JoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        if(Integer.parseInt(args[2].toString()) == 0) {
            String recommendKey = "RECOMMONDPOST-USER:" + args[1].toString();
            String startKey = "PAGE-START:" + args[1].toString();
            List<IndexPost> indexPostList = new ArrayList<>();
            Integer length;
            length = RecommendAlgorithm.indexRecommend(Long.valueOf(args[1].toString()), indexPostList);
            logger.info("开始刷新recommendKey={}的redis缓存............", recommendKey);
            redisTemplate.opsForValue().set(recommendKey, JSONArray.toJSONString(indexPostList), Resources.getCacheTime(), Resources.getRedisTimeType());
            logger.info("开始刷新startKey={}的redis缓存............", startKey);
            redisTemplate.opsForValue().set(startKey, length, Resources.getCacheTime(), Resources.getRedisTimeType());
            logger.info("刷新完成.......");
        }
    }


//    @Before("UserQuestionPointCut()")
//    public void UserQuestionBefore(JoinPoint joinPoint) throws Throwable {
//        System.out.println("调用Aop清除缓存。。。。");
//        Object[] args = joinPoint.getArgs();
//        QuestionEntity questionById = questionRepository.findQuestionById((String) args[1]);
//        CaffeineCache caffeineCache = (CaffeineCache) cacheManagerConfig.getCacheManager().getCache("userquestionCount");
//        Cache<Object, Object> nativeCache = caffeineCache.getNativeCache();
//        ConcurrentMap<Object, Object> objectObjectConcurrentMap = nativeCache.asMap();
//        for (Object o : objectObjectConcurrentMap.keySet()) {
//            String key = (String) o;
//            key = key.split("#")[1].split("]")[0];
//            if (key.equals(String.valueOf(questionById.getStage())) || key.equals(questionById.getId())) {
//                cacheManagerConfig.getCacheManager().getCache("userquestionCount").evict((String) o);
//
//            }
//        }
//    }

//    @Pointcut(" execution(public * com.youdao.adaplearnserver.service.FavoriteService.saveCollection(..)) " +
//            "|| execution(public * com.youdao.adaplearnserver.service.FavoriteService.updateFavorite(..)) " +
//            "|| execution(public * com.youdao.adaplearnserver.service.FavoriteService.cancelFavorite(..))")
//    public void FavoritePointCut() {
//    }
//
//    @Before("FavoritePointCut()")
//    public void FavoriteBefore(JoinPoint joinPoint) throws Throwable {
//        Object[] args = joinPoint.getArgs();
//        String key = "[" + args[0].toString() + "#" + args[1].toString() + "]";
//        cacheManagerConfig.getCacheManager().getCache("IsfavoriteQuestion").evict(key);
//    }
}
